﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Threading;
using System.Globalization;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Drawing.Drawing2D;
using System.Management;
using HuynhQuangWebsite.Models;
namespace HuynhQuangWebsite.Controllers
{
    public  class BaseController : Controller
    {
       // protected override void ExecuteCore()
        //{
        //    if (RouteData.Values["lang"] != null &&
        //        !string.IsNullOrWhiteSpace(RouteData.Values["lang"].ToString()))
        //    {
        //        // set the culture from the route data (url)
        //        var lang = RouteData.Values["lang"].ToString();
        //        Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(lang);
        //    }
        //    else
        //    {
        //        // load the culture info from the cookie
        //        var cookie = HttpContext.Request.Cookies["THS.CurrentUICulture"];
        //        var langHeader = string.Empty;
        //        if (cookie != null)
        //        {
        //            // set the culture by the cookie content
        //            langHeader = cookie.Value;
        //            Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(langHeader);
        //        }
        //        else
        //        {
        //            // set the culture by the location if not speicified
        //            langHeader = HttpContext.Request.UserLanguages[0];
        //            Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(langHeader);
        //        }
        //        // set the lang value into route data
        //        RouteData.Values["lang"] = langHeader;
        //    }

        //    // save the location into cookie
        //    HttpCookie _cookie = new HttpCookie("THS.CurrentUICulture", Thread.CurrentThread.CurrentUICulture.Name);
        //    _cookie.Expires = DateTime.Now.AddYears(1);
        //    HttpContext.Response.SetCookie(_cookie);

          //  base.ExecuteCore();
        //}
        protected override RedirectResult Redirect(string url)
        {
            return new AjaxAwareRedirectResult(url);
        }
        public class AjaxAwareRedirectResult : RedirectResult
        {
            public AjaxAwareRedirectResult(string url)
                : base(url)
            {
            }

            public override void ExecuteResult(ControllerContext context)
            {
                if (context.RequestContext.HttpContext.Request.IsAjaxRequest())
                {
                    string destinationUrl = UrlHelper.GenerateContentUrl(Url, context.HttpContext);

                    JavaScriptResult result = new JavaScriptResult()
                    {
                        Script = String.Format("window.location='{0}';", destinationUrl)
                    };
                    result.ExecuteResult(context);
                }
                else
                    base.ExecuteResult(context);
            }
        }
        public bool IsAuthenticateAdmin()
        {
            if (Session["Admin"] == null)
                return false;
            int adminID = 0;
            Int32.TryParse(Session["Admin"].ToString(), out adminID);
            huynhquangco_websiteEntities ctx = new huynhquangco_websiteEntities();
            Models.Admin adm = ctx.Admins.SingleOrDefault(p => p.AdminID == adminID);
            if (adm.PCIP.Equals(GetCookie()))
                return true;
            return false;

        }
        public string GetCookie()
        {
            //String cookie = HttpContext.Request.ServerVariables["HTTP_COOKIE"];
            //if (cookie.Length >= 500)
            //    return cookie.Substring(100, cookie.Length - 100);
            //return cookie;
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            string MACAddress = String.Empty;
            foreach (ManagementObject mo in moc)
            {
                if (MACAddress == String.Empty) // only return MAC Address from first card
                {
                    if ((bool)mo["IPEnabled"] == true) MACAddress = mo["MacAddress"].ToString();
                }
                mo.Dispose();
            }

           MACAddress = MACAddress.Replace(":", "");
           return MACAddress;
        }
        //public string GetCookie()
        //{
        //    //String cookie = HttpContext.Request.ServerVariables["LOGON_USER"];
        //    String cookie = HttpContext.Request.ServerVariables["HTTP_COOKIE"];
        //    if (cookie.Contains("ASP.NET_SessionId"))
        //    {
        //        int index = cookie.IndexOf("ASP.NET_SessionId");
        //        //int lenght=cookie.Substring(0,index).Length;
        //        return cookie.Substring(index, cookie.Length - (index));
        //    }
        //    return HttpContext.Request.ServerVariables["HTTP_COOKIE"];
        //}
        public static bool IsImageFile(string fileName)
        {
            FileInfo info = new FileInfo(fileName);
            string extention = info.Extension.ToLower();
            if (extention == ".jpg" || extention == ".gif" || extention == ".png")
                return true;
            else
                return false;
        }
        public static bool IsVideo(string fileName)
        {
            FileInfo info = new FileInfo(fileName);
            string extention = info.Extension.ToLower();
            if (extention == ".flv")
                return true;
            else
                return false;
        }
        // Delete file
        public static void DeleteFile(HttpRequestBase requestBase, String virtualPath, String fileName)
        {
            String Name = System.IO.Path.GetFileName(fileName);
            String virtualFullPath = virtualPath + "/" + Name;
            String filePath = Path.Combine(requestBase.MapPath(virtualFullPath));
            FileInfo info = new FileInfo(filePath);
            if (info.Exists)
                info.Delete();
        }
        public static String GenerateImageName(HttpRequestBase requestBase, String virtualPath, String fileName, String userID)
        {

            FileInfo fileInfo = new FileInfo(fileName);
            //get extension file
            String extension = fileInfo.Extension;
            //gen name with user id
            fileName = "Images" + userID;
            String sFileName = fileName + extension;
            int file_append = 0;
            while (System.IO.File.Exists(Path.Combine(requestBase.MapPath(String.Format("{0}/{1}", virtualPath, sFileName)))))
            {
                file_append++;
                sFileName = fileName + file_append + extension;
            }
            return sFileName;
        }
        public static String GenerateFileNameByNo(HttpRequestBase requestBase, String virtualPath, String fileName, String No)
        {

            FileInfo fileInfo = new FileInfo(fileName);
            //get extension file
            String extension = fileInfo.Extension;
            //gen name with user id
            fileName = No;
            String sFileName = fileName + extension;
            int file_append = 0;
            while (System.IO.File.Exists(Path.Combine(requestBase.MapPath(String.Format("{0}/{1}", virtualPath, sFileName)))))
            {
                file_append++;
                sFileName = fileName + file_append + extension;
            }
            return sFileName;
        }

        //resize image
        public static bool ResizeImage(string originalFile, int newWidth, int newHeight, int resizeQuanlityPercent)
        {
            //Load the file
            System.Drawing.Image img = System.Drawing.Image.FromFile(originalFile);
            Size sizeOriginalImage = img.Size;	//To return as out parameter
            Size sizePhoto = new Size(newWidth, newHeight);
            bool blnSuccess = ResizeAnImage(ref img, sizePhoto, originalFile, resizeQuanlityPercent);
            img.Dispose();
            return true; ;
        }
        //
        public static bool ResizeImage(Stream stream, String originalFilePath,int newWidth, int newHeight, int resizeQuanlityPercent)
        {
            //Load the file
            System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
            Size sizeOriginalImage = img.Size;	//To return as out parameter
            Size sizePhoto = new Size(newWidth, newHeight);
            bool blnSuccess = ResizeAnImage(ref img, sizePhoto, originalFilePath, resizeQuanlityPercent);
            img.Dispose();
            return true; ;
        }
        //
        public static bool MakeImagesAndThumbFile(Stream stream, string newPhotoPath, string thumbPath, int newWidth, int newHeight, int thumbWidth, int thumbHeight, int resizeQuanlityPercent)
        {
            //Load the file
            System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
            Size sizeOriginalImage = img.Size;	//To return as out parameter
            Size sizeThumb = new Size(thumbWidth, thumbHeight);  //thumbs are actually limited only by height
            ResizeAnImage(ref img, sizeThumb, thumbPath,  resizeQuanlityPercent);
            Size sizePhoto = new Size(newWidth, newHeight);
            bool blnSuccess = ResizeAnImage(ref img, sizePhoto, newPhotoPath, resizeQuanlityPercent);
            img.Dispose();
            return true; ;
        }
        public static bool MakeImagesAndThumbFile(string originalFile, string newPhotoPath, string thumbPath, int newWidth, int newHeight, int thumbWidth, int thumbHeight, int resizeQuanlityPercent)
        {
            //Load the file
            System.Drawing.Image img = System.Drawing.Image.FromFile(originalFile);
            Size sizeOriginalImage = img.Size;	//To return as out parameter
            Size sizeThumb = new Size(thumbWidth, thumbHeight);  //thumbs are actually limited only by height
            ResizeAnImage(ref img, sizeThumb, thumbPath, resizeQuanlityPercent);
            Size sizePhoto = new Size(newWidth, newHeight);
            bool blnSuccess = ResizeAnImage(ref img, sizePhoto, newPhotoPath, resizeQuanlityPercent);
            img.Dispose();
            return true; ;
        }
        //
        private static bool ResizeAnImage(ref System.Drawing.Image img, Size sizeNew, string filePath, int resizeQuanlityPercent)
        {
            int intOrigWidth = img.Width;
            int intOrigHeight = img.Height;
            int intNewWidth = sizeNew.Width;
            int intNewHeight = sizeNew.Height;
            if (intOrigWidth < intNewWidth && intOrigHeight < intNewHeight)
            {
                //image is smaller than resized should be, do nothing
                //System.IO.File.Copy(strOriginalFile, filePath, true);
                //
                //Make a bitmap for the result
                Image imgNew = new Bitmap(intOrigWidth, intOrigHeight, img.PixelFormat);
                //Make a Graphics object for the result Bitmap
                Graphics oGraphic = Graphics.FromImage(imgNew);
                oGraphic.CompositingQuality = CompositingQuality.HighQuality;
                oGraphic.SmoothingMode = SmoothingMode.HighQuality;
                oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                Rectangle oRectangle = new Rectangle(0, 0, intOrigWidth, intOrigHeight);
                oGraphic.DrawImage(img, oRectangle);
                // Encoder parameter for image quality (thanks Dmitry A. Mottl)
                EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)resizeQuanlityPercent);
                // Jpeg image codec
                ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");
                EncoderParameters encoderParams = new EncoderParameters(1);
                encoderParams.Param[0] = qualityParam;
                imgNew.Save(filePath, jpegCodec, encoderParams);

                //imgNew.Save(strFile, ImageFormat.Jpeg); 
                imgNew.Dispose();
                return false;
            }
            else
            {
                float flWidth2Height = (float)intOrigWidth / (float)intOrigHeight;
                float flNewWidth2Height = (float)intNewWidth / (float)intNewHeight;
                if (flWidth2Height > flNewWidth2Height)
                {
                    //Horizontal, make height smaller then in spec
                    //Use width to calc the scale
                    float flScale = (float)intNewWidth / (float)intOrigWidth;
                    intNewHeight = System.Convert.ToInt32(flScale * intOrigHeight);
                }
                else
                {
                    //Vertical, make width smaller then in spec
                    //Use height to calc the scale
                    float flScale = (float)intNewHeight / (float)intOrigHeight;
                    intNewWidth = System.Convert.ToInt32(flScale * intOrigWidth);
                }
                //Make a bitmap for the result
                Image imgNew = new Bitmap(intNewWidth, intNewHeight, img.PixelFormat);
                //Make a Graphics object for the result Bitmap
                Graphics oGraphic = Graphics.FromImage(imgNew);
                oGraphic.CompositingQuality = CompositingQuality.HighQuality;
                oGraphic.SmoothingMode = SmoothingMode.HighQuality;
                oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                Rectangle oRectangle = new Rectangle(0, 0, intNewWidth, intNewHeight);
                oGraphic.DrawImage(img, oRectangle);

                // Encoder parameter for image quality (thanks Dmitry A. Mottl)
                EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)resizeQuanlityPercent);
                // Jpeg image codec
                ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");
                EncoderParameters encoderParams = new EncoderParameters(1);
                encoderParams.Param[0] = qualityParam;
                imgNew.Save(filePath, jpegCodec, encoderParams);

                //imgNew.Save(strFile, ImageFormat.Jpeg); 
                imgNew.Dispose();
                return true;
            }
        }
        private static ImageCodecInfo GetEncoderInfo(string mimeType)
        {
            // Get image codecs for all image formats
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

            // Find the correct image codec
            for (int i = 0; i < codecs.Length; i++)
                if (codecs[i].MimeType == mimeType)
                    return codecs[i];
            return null;
        }
        /// <summary>
        /// Format used to save resized image.
        /// </summary>
        public static ImageFormat SaveFormat = ImageFormat.Jpeg;
        /// <summary>
        /// hieu.nguyen 
        /// </summary>
        /// <param name="source">InpustStream</param>
        /// <param name="target">filename to save</param>
        /// <param name="MaxX">Width size</param>
        /// <param name="MaxY">Height size</param>
        /// <param name="isTrimImage">trim to fix image</param>
        /// <returns>true if save to file sucessful</returns>
        /// 
        public static bool ResizeImage(Stream source, string target, int MaxX, int MaxY, bool isTrimImage)
        {
            using (Image src = Image.FromStream(source, true))
            {
                // Check that we have an image
                if (src != null)
                {
                    int origX, origY, newX, newY;
                    int trimX = 0, trimY = 0;

                    // Default to size of source image
                    newX = origX = src.Width;
                    newY = origY = src.Height;

                    // Does image exceed maximum dimensions?
                    if (origX > MaxX || origY > MaxY)
                    {
                        // Need to resize image
                        if (isTrimImage)
                        {
                            // Trim to exactly fit maximum dimensions
                            double factor = Math.Max((double)MaxX / (double)origX,
                                (double)MaxY / (double)origY);
                            newX = (int)Math.Ceiling((double)origX * factor);
                            newY = (int)Math.Ceiling((double)origY * factor);
                            trimX = newX - MaxX;
                            trimY = newY - MaxY;
                        }
                        else
                        {
                            // Resize (no trim) to keep within maximum dimensions
                            double factor = Math.Min((double)MaxX / (double)origX,
                                (double)MaxY / (double)origY);
                            newX = (int)Math.Ceiling((double)origX * factor);
                            newY = (int)Math.Ceiling((double)origY * factor);
                        }
                    }

                    // Create destination image
                    using (Image dest = new Bitmap(newX - trimX, newY - trimY))
                    {
                        Graphics graph = Graphics.FromImage(dest);
                        graph.InterpolationMode =
                            System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        graph.DrawImage(src, -(trimX / 2), -(trimY / 2), newX, newY);
                        dest.Save(target, SaveFormat);
                        // Indicate success
                        return true;
                    }
                }
            }
            // Indicate failure
            return false;
        }
    }
}
